<?php
require 'database.php';
$db = new DB();

$array = array('.', ':', ' ');

$Qry = 'SELECT g.g_id, g.g_url, g.g_image
		FROM games g
		WHERE images IS NULL OR images = ""
		ORDER BY g.g_id DESC
		LIMIT 10';

$total_img = $db->numRows($Qry);

if ($total_img) {
	$res = $db->fetchAll($Qry);

	foreach ($res as $key=>$value) {
		$condition = 'g_id = ' . $value['g_id'];
		$imgurl = $value['g_image'];

//		echo $imgurl . '<br />';

		$file_parts = pathinfo($imgurl);
		$file_extension = $file_parts['extension'];

		$path = $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/';
		$new_file = $value['g_url'];
		$new_file = str_replace($array, '', $new_file);
		$new_file = str_replace('_', '-', $new_file);
		$new_file = $new_file . '.' . $file_extension;

		if (file_exists($path . $new_file)) {
			$data = array(
					'images'=>$new_file
			);
			$renewIMG = $db->update('games', $data, $condition);

			if ($renewIMG)
				echo $key . ' <font color="red">- /data/uploads/' . $new_file . ' ==> Reupdated</font><br />';

			continue;
		}
		$image = getimg($imgurl);
		file_put_contents($path . $new_file, $image);

		$data = array(
				'images'=>$new_file
		);

// 		var_dump($data);

		$newIMG = $db->update('games', $data, $condition);

		if ($newIMG)
			echo $key . ' <font color="green">- /data/uploads/' .$new_file . ' ==> Add New</font><br />';
	}
}

function getimg($url) {
	$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
	$headers[] = 'Connection: Keep-Alive';
	$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';

	$user_agent = 'php';

	$process = curl_init($url);

	curl_setopt($process, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
	curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($process, CURLOPT_HEADER, 0);
	curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
	curl_setopt($process, CURLOPT_TIMEOUT, 30);
	curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);

	$return = curl_exec($process);

	curl_close($process);

	return $return;
}